import { defineStore } from 'pinia'
import { ref, computed, watch } from 'vue'
import { login, logout } from '../api/auth.js'

// APP端缓存key
const TOKEN_KEY = 'app_token'
const USER_INFO_KEY = 'app_user_info'

export const useUserStore = defineStore('user', () => {
  // 从本地存储初始化数据
  const token = ref(localStorage.getItem(TOKEN_KEY) || '')
  const userInfo = ref(JSON.parse(localStorage.getItem(USER_INFO_KEY)) || null)

  // 计算属性：判断是否是医生
  const isDoctor = computed(() => userInfo.value?.roleId === 2)
  // 获取用户角色ID
  const roleId = computed(() => userInfo.value?.roleId || 0)

  // 监听数据变化，自动保存到本地存储
  watch(token, (newToken) => {
    if (newToken) {
      localStorage.setItem(TOKEN_KEY, newToken)
    } else {
      localStorage.removeItem(TOKEN_KEY)
    }
  })

  watch(userInfo, (newUserInfo) => {
    if (newUserInfo) {
      localStorage.setItem(USER_INFO_KEY, JSON.stringify(newUserInfo))
    } else {
      localStorage.removeItem(USER_INFO_KEY)
    }
  }, { deep: true })

  // 设置用户信息
  const setUserInfo = (info) => {
    userInfo.value = info
  }

  // 设置token
  const setToken = (newToken) => {
    token.value = newToken
  }

  // 登录
  const userLogin = async (loginForm) => {
    try {
      const { data } = await login(loginForm)
      setToken(data.token)
      setUserInfo(data.userInfo)
      return data
    } catch (error) {
      throw error
    }
  }

  // 登出
  const userLogout = async () => {
    try {
      // 先清除本地数据，再调用登出接口
      setToken('')
      setUserInfo(null)
      localStorage.removeItem(TOKEN_KEY)
      localStorage.removeItem(USER_INFO_KEY)
      
      // 尝试调用登出接口，但不影响本地登出
      try {
        await logout()
      } catch (error) {
        console.warn('登出接口调用失败:', error)
      }
    } catch (error) {
      console.error('登出失败:', error)
      // 即使出错也要清除本地数据
      setToken('')
      setUserInfo(null)
      localStorage.removeItem(TOKEN_KEY)
      localStorage.removeItem(USER_INFO_KEY)
    }
  }

  return {
    token,
    userInfo,
    isDoctor,
    roleId,
    setUserInfo,
    setToken,
    userLogin,
    userLogout
  }
}, {
  persist: {
    enabled: true,
    strategies: [
      {
        key: 'user',
        storage: localStorage,
        paths: ['token', 'userInfo']
      }
    ]
  }
})
